package com.bawei.mall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.domain.MallProductAddress;
import com.bawei.mall.user.mapper.CompletionAddressMapper;
import com.bawei.mall.user.service.CompletionAddressService;
import com.bawei.mall.user.utils.Addr;
import com.bawei.system.domain.model.LoginUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.mall.user.service.impl
 * @Project：mall_cloud
 * @name：CompletionAddressServiceImpl
 * @Date：2024/6/29 11:49
 */
@Service
@Log4j2
public class CompletionAddressServiceImpl implements CompletionAddressService {
    @Autowired
    private CompletionAddressMapper completionAddressMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ACCESS_TOKEN="login_tokens:";



    @Override
    @Transactional
    public void add(MallProductAddress mallProductAddress) {
        //获取登录人id
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        System.out.println(userKey);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        mallProductAddress.setUserId(Integer.valueOf(String.valueOf(cusUser.getUserId())));
        //默认状态
        if(mallProductAddress.getDefaultStatus()==1){
            //修改状态
            completionAddressMapper.updateStatus();
        }
        completionAddressMapper.add(mallProductAddress);
    }

    private String getTokenKey(String key)
    {
        return ACCESS_TOKEN + key;
    }



    @Override
    public List<MallProductAddress> fetchAddressList() {
        return         completionAddressMapper.fetchAddressList();
    }

    @Override
    public void del(Integer id) {
        completionAddressMapper.del(id);
    }

    @Override
    public MallProductAddress findAddressById(Integer id) {
        return completionAddressMapper.findAddressById(id);
    }


    @Override
    @Transactional
    public void updateAddress(MallProductAddress mallProductAddress) {
        //默认状态
        if(mallProductAddress.getDefaultStatus()==1){
            //修改状态
            completionAddressMapper.updateStatus();
        }
        completionAddressMapper.updateAddress(mallProductAddress);
    }


}
